<?php


namespace app\common\service;


use app\common\model\SystemLog;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use app\common\model\SmsCode;

class SmsService
{
    protected $config;

    /**
     * Sms constructor.
     * @param $sign_name
     */
    public function __construct($sign_name = null)
    {
        $this->config = [
            // HTTP 请求的超时时间（秒）
            'timeout'  => 5.0,

            // 默认发送配置
            'default'  => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],
                'aliyun'   => [
                    'access_key_id'     => app()->env->get('ali_sms_access_key_id'),
                    'access_key_secret' => app()->env->get('ali_sms_access_key_secret'),
                    'sign_name'         => $sign_name ?? app()->env->get('ali_sms_sign_name'),
                ],
            ],
        ];
    }

    /**
     * 短信验证码
     * @Author zengxin(573908667@qq.com)
     * @param $mobile
     * @param $code
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function aliSms($mobile, $code)
    {
        try {
            $easy_sms = new EasySms($this->config);
            $easy_sms->send($mobile, [
                'template' => app()->env->get('ali_sms_template_id'),
                'data'     => [
                    'code' => $code
                ],
            ]);

            SmsCode::create([
                'mobile'      => $mobile,
                'code'        => $code,
                'create_time' => time(),
                'expire_time' => time() + 5 * 60,
            ]);

            return true;
        } catch (NoGatewayAvailableException $e) {
            SystemLog::log($e->getException('aliyun'), '', 'sms', 'error');
            return false;
        }
    }

    /**
     * 阿里云短信通知
     * @Author zengxin(573908667@qq.com)
     * @param $mobile
     * @param $data
     * @param $template
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function aliSmsMsg($mobile, $data, $template)
    {
        try {
            $easy_sms = new EasySms($this->config);
            $easy_sms->send($mobile, [
                'template' => $template,
                'data'     => $data,
            ]);
            return true;
        } catch (NoGatewayAvailableException $e) {
            SystemLog::log($e->getException('aliyun'), '', 'sms', 'error');
            return false;
        }
    }
}